package com.rtx.common;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.annotation.TableField;
import com.rtx.api.annotation.RtxMybatisIgnore;

@SuppressWarnings("all")
public class EdiBeanUtils {
	
	static Logger logger = LoggerFactory.getLogger(EdiBeanUtils.class);

	public static Object copyFields(Map<String,Object> map,Class clazz) throws Exception{
		List<Field> fieldArray = new ArrayList<Field>();
		List list1 = Arrays.asList(clazz.getSuperclass().getDeclaredFields());
		List list2 = Arrays.asList(clazz.getDeclaredFields());
		fieldArray.addAll(list1);
		fieldArray.addAll(list2);
		
		Object ob = clazz.newInstance();
		
		for(Field f:fieldArray) {
			if(map.get(f.getName()) != null) {
				try {
					f.setAccessible(true);
					if(Double.class.equals(f.getType())) {
						f.set(ob,Double.parseDouble(map.get(f.getName())+""));
					}else if(Integer.class.equals(f.getType())){
						f.set(ob,Integer.parseInt(map.get(f.getName())+""));
					}else if(Long.class.equals(f.getType())){
						f.set(ob,Long.parseLong(map.get(f.getName())+""));
					}else if(LocalDateTime.class.equals(f.getType())){
						try {
							f.set(ob,Long.parseLong(map.get(f.getName())+""));
						} catch (Exception e) {
						}

					}else {
						f.set(ob,String.valueOf(map.get(f.getName())));
					}
				} catch (Exception e) {
					logger.error("字段-{}设置值-{}-异常",f.getName(),map.get(f.getName()),e);
				}
				
			}

		}
		
		return ob;
	}
	
	public static String getCoulmns(Class clazz) throws Exception{
		List<Field> fieldArray = new ArrayList<Field>();
		List list1 = Arrays.asList(clazz.getSuperclass().getDeclaredFields());
		List list2 = Arrays.asList(clazz.getDeclaredFields());
		fieldArray.addAll(list1);
		fieldArray.addAll(list2);
		List<String> list = new ArrayList<>();


		for(Field field:fieldArray) {
			String columnname = field.getName();
			
			RtxMybatisIgnore ignore = field.getDeclaredAnnotation(RtxMybatisIgnore.class);
			if(null !=ignore) {
				continue; 
			}

			TableField tableField =  field.getDeclaredAnnotation(TableField.class);
			if(tableField != null) {
				if(!tableField.exist()) {
					continue;
				}
				if(tableField.value() != null) {
					columnname = tableField.value();
				}
			}
			
			list.add(columnname.replaceAll("([a-z])([A-Z]+)", "$1_$2").toLowerCase());
		}
		return list.stream().collect(Collectors.joining(","));
	}
}
